package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.EmployeeException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;



@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5Password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public void addEmployee(EmployeeDTO employeeDTO) {
        // 1.简单的校验
        //账号不能为空
        if (Objects.isNull(employeeDTO.getUsername())){
            throw new EmployeeException(MessageConstant.USER_NAME_IS_NULL);
        }
        //账号唯一
        Integer count = employeeMapper.selectCountByUserName(employeeDTO.getUsername());
        if (count != 0){
            throw new EmployeeException(MessageConstant.USER_NAME_NOT_ONLY);
        }
        //判断手机号是否规范
        if (!Pattern.matches("^1[3456789]\\d{9}$",employeeDTO.getPhone())){
            throw new EmployeeException(MessageConstant.PHONE_NOT_LEGAL);
        }
        //身份证
        if (!Pattern.matches("^[1-9]\\d{5}(19|20)\\d{2}(0[1-9]|10|11|12)([012]\\d|3[01])\\d{3}[0-9xX]$",employeeDTO.getIdNumber())){
            throw new EmployeeException(MessageConstant.ID_NUMBER_NOT_LEGAL);
        }

        // 2.封装数据
        //数据转换
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        employee.setIdNumber(employeeDTO.getIdNumber());
       /* employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());*/
        //密码设为默认密码
        String md5Password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(md5Password);
        //设置状态
        employee.setStatus(1);  // 默认状态为1

        //3.添加到数据库
        employeeMapper.addEmployee(employee);
    }

    @Override
    public PageResult pageQueryEmployee(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        List<Employee> employeeList = employeeMapper.pageQueryEmployeeByName(employeePageQueryDTO.getName());
        PageInfo<Employee> pageInfo = new PageInfo<>(employeeList);

        PageResult pageResult = new PageResult();
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setRecords(employeeList);
        return pageResult;
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        Employee employee = new Employee();
        employee.setId(id);
        employee = employeeMapper.getEmpByEmployee(employee);
        employee.setStatus(status);
        employeeMapper.updateEmpByEmployeeId(employee);
    }

    @Override
    public Employee queryEmployee(Long id) {
        Employee employee = new Employee();
        employee.setId(id);
        employee = employeeMapper.getEmpByEmployee(employee);
        return employee;
    }

    @Override
    public void updateEmployee(EmployeeDTO employeeDTO) {
        // 简单的校验
        //账号不能为空
        if (Objects.isNull(employeeDTO.getUsername())){
            throw new EmployeeException(MessageConstant.USER_NAME_IS_NULL);
        }
        //账号唯一
        Integer count = employeeMapper.selectCountByUserNameNotSelf(employeeDTO.getId(),employeeDTO.getUsername());
        if (count != 0){
            throw new EmployeeException(MessageConstant.USER_NAME_NOT_ONLY);
        }
        //判断手机号是否规范
        if (!Pattern.matches("^1[3456789]\\d{9}$",employeeDTO.getPhone())){
            throw new EmployeeException(MessageConstant.PHONE_NOT_LEGAL);
        }
        //身份证
        if (!Pattern.matches("^[1-9]\\d{5}(19|20)\\d{2}(0[1-9]|10|11|12)([012]\\d|3[01])\\d{3}[0-9xX]$",employeeDTO.getIdNumber())){
            throw new EmployeeException(MessageConstant.ID_NUMBER_NOT_LEGAL);
        }
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        employee.setIdNumber(employeeDTO.getIdNumber());
        employeeMapper.updateEmpByEmployeeId(employee);
    }

}
